package com.example.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.controller.FileController;
import com.example.entity.Account;
import com.example.entity.Business;
import com.example.entity.Delivery;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.DeliveryMapper;
import com.example.mapper.UserMapper;
import com.example.utils.MD5Util;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class DeliveryService {

    @Resource
    private DeliveryMapper deliveryMapper;

    @Resource
    private FileController file;

    /**
     * 新增
     */
    public void add(Delivery delivery) {
        Delivery dbDelivery = deliveryMapper.selectByUsername(delivery.getUsername());
        if (ObjectUtil.isNotNull(dbDelivery)) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        if (ObjectUtil.isEmpty(delivery.getName())) {
            delivery.setName(delivery.getUsername());
        }
        String http = "http://" + file.getIp() + ":" + file.getPort() + "/files/";
        delivery.setAvatar(http + "userDefault.png");
        delivery.setRole(RoleEnum.DELIVERY.name());
        if (ObjectUtil.isEmpty(delivery.getPassword())) {
            //获取随机盐
            String salt= MD5Util.getSaltString();
            //密码、盐一起加密，将加盐加密的密码存入库
            delivery.setPassword(Constants.USER_DEFAULT_PASSWORD);
            delivery.setPassword(MD5Util.toMD5String(delivery.getPassword(),salt));
            //盐一起存入库
            delivery.setSalt(salt);
        }
        deliveryMapper.insert(delivery);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        deliveryMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            deliveryMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Delivery delivery) {

        delivery.setPassword(null);
        Delivery dbDelivery = deliveryMapper.selectByUsername(delivery.getUsername());

        //对输入的密码进行md5加密
        if(ObjectUtil.isNotEmpty(delivery.getPassword())){
            String salt = MD5Util.getSaltString();
            String password = MD5Util.toMD5String(delivery.getPassword(),salt);
            delivery.setPassword(password);
            delivery.setSalt(salt);
        }
        //  根据当前更新的用户的账号查询数据库  如果数据库存在跟当前更新用户一样账号的数据  那么当前的更新是不合法的  数据重复了
        if (ObjectUtil.isNotEmpty(dbDelivery) && !Objects.equals(dbDelivery.getId(), delivery.getId())) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        deliveryMapper.updateById(delivery);
    }

    /**
     * 根据ID查询
     */
    public Delivery selectById(Integer id) {
        return deliveryMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Delivery> selectAll(Delivery delivery) {
        return deliveryMapper.selectAll(delivery);
    }

    /**
     * 分页查询
     */
    public PageInfo<Delivery> selectPage(Delivery delivery, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Delivery> list = deliveryMapper.selectAll(delivery);
        return PageInfo.of(list);
    }

    /**
     * 用户登录
     */
    public Account login(Account account) {
        Delivery dbDelivery = this.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbDelivery)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!dbDelivery.getPassword().equals(MD5Util.toMD5String(account.getPassword(),dbDelivery.getSalt()))) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String tokenData = dbDelivery.getId() + "-" + RoleEnum.DELIVERY.name();
        String token = TokenUtils.createToken(tokenData, dbDelivery.getPassword());
        dbDelivery.setToken(token);
        return dbDelivery;
    }

    /**
     *  用户查询
     */
    public Delivery selectByUsername(String username){
        Delivery delivery = new Delivery();
        delivery.setUsername(username);
        List<Delivery> deliveryList = this.selectAll(delivery);
        return CollUtil.isEmpty(deliveryList) ? null : deliveryList.get(0);
    }

    /**
     * 计数
     */
    public int countDelivery(Delivery delivery) {
        return deliveryMapper.countOnlineDelivery(delivery);
    }

    public void updatePassword(Account account) {
        Delivery dbDelivery = this.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbDelivery)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!dbDelivery.getPassword().equals(MD5Util.toMD5String(account.getPassword(),dbDelivery.getSalt()))) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        String salt = MD5Util.getSaltString();
        String newPassword =MD5Util.toMD5String(account.getNewPassword(),salt);
        dbDelivery.setPassword(newPassword);
        dbDelivery.setSalt(salt);
        deliveryMapper.updateById(dbDelivery);
    }
}
